package com.dtguai.app.common.exception;

import com.dtguai.app.common.error.ErrorCode;
import com.dtguai.app.util.IpUtils;
import com.dtguai.app.util.redis.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理器
 *
 * @author guoLiang
 * @date 2019年6月25日09:36:12
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.dtguai.app")
@AllArgsConstructor
public class DefinedExceptionHandler {

    private final RedisUtil redisUtil;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(DefinedException.class)
    public DefinedMap handleDefinedException(DefinedException e) {
        DefinedMap dm = new DefinedMap();
        dm.put("code", e.getCode());
        dm.put("msg", e.getMessage());
        return dm;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public DefinedMap handlerNoFoundException(Exception e, HttpServletRequest request) {
        String ip = IpUtils.getIpAddress(request);
        String blacklist_ip_hash_key = "blacklist_ip_hash_key";
        Object cnt = redisUtil.getHash(blacklist_ip_hash_key, ip);
        int cntInt = cnt == null ? 0 : Integer.parseInt(cnt.toString());
        redisUtil.setHash(blacklist_ip_hash_key, ip, cntInt + 1);
        log.error(ip + "----" + e.getMessage(), ip + "----" + e);
        return DefinedMap.error(ErrorCode.NOT_FOUND);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public DefinedMap handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return DefinedMap.error(ErrorCode.REPETITION);
    }

    @ExceptionHandler(Exception.class)
    public DefinedMap handleException(Exception e) {
        log.error(e.getMessage(), e);
        return DefinedMap.error();
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public DefinedMap handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.info(e.getMessage(), e);
        return DefinedMap.error(ErrorCode.HTTP_REQUEST_METHOD_NOT_SUPPORTED);
    }

    @ExceptionHandler(IllegalStateException.class)
    public DefinedMap handleIllegalStateException(String msg, Exception e) {
        log.info(e.getMessage(), e);
        return DefinedMap.error();
    }
}
